import { messages, getToken } from "share/common";
import React from "react";
import { connect } from "react-redux";
import moment from "moment";
import travelService from "containers/request/travel-request/travel.service";
import Condition from "components/condition";
import { Button, Modal, Alert, Icon, message, Spin } from "antd";
import VendorCard from "./vendor-card";
import "styles/request/travel-request/comp/multiple-vendor-selector.scss";
import errorMessage from "share/errorMessage";

const { If } = Condition;
const businessTypeMap = {
  2001: "airlines",
  2002: "train",
  2003: "hotel",
  2004: "car",
};

export default class MultipleVendorSelector extends React.Component {
  state = {
    loading: false,
    vendors: [],
  };
  componentWillReceiveProps(nextProps) {
    if (nextProps.visible === true) {
      this.fetchSyncResult();
    }
  }

  onCancel = () => {
    this.props.onClose && this.props.onClose();
  };
  fetchSyncResult = () => {
    const { params = {} } = this.props;
    let { businessCode = "", businessType = "" } = params;
    this.setState({
      loading: true,
    });
    travelService
      .getVendorsSyncResult({
        businessCode,
        businessType: businessTypeMap[businessType],
      })
      .then((res) => {
        if (res.data && res.data.body) {
          this.setState({
            vendors: res.data.body,
          });
        }
      })
      .catch(() => {
        message.error(messages("request-1.key881") /*加载失败*/);
      })
      .finally(() => {
        this.setState({
          loading: false,
        });
      });
  };

  bookHandler = (vendorItem) => {
    const { params = {} } = this.props;
    let { businessCode = "" } = params;
    const paramsData = {
      supplierOID: vendorItem.supplierOid,
      supplierType: vendorItem.supplierType,
      businessCode,
      direction: "web",
      pageType: 1002,
    };
    let timestamp = new Date().getTime();
    let token = JSON.parse(getToken()).access_token;
    this.setState({
      loading: true,
    });

    travelService
      .getBookTicketSSOUrl(paramsData)
      .then((res) => {
        if (res.data && res.data.url) {
          let url = res.data.url;
          if (url.indexOf("?") > -1) {
            url += `&`;
          } else {
            url += `?`;
          }
          url += `access_token=${token}&timestamp=${timestamp}&businessCode=${params.businessCode}`;
          window.open(url);
        }
      })
      .catch((err) => {
        errorMessage(err.response);
      })
      .finally(() => {
        this.setState({
          loading: false,
        });
      });
  };

  renderVenderCards = (list) => {
    const { params = {} } = this.props;
    const { businessCode = "" } = params;
    return (
      <div className="card-container">
        {list.map((vendor, i) => (
          <VendorCard businessCode={businessCode} vendor={vendor} index={i} book={this.bookHandler} />
        ))}
      </div>
    );
  };

  render() {
    const { vendors, loading } = this.state;
    const { visible, params = {} } = this.props;
    const { businessCode = "", businessType = "" } = params;

    const succeedList = vendors.filter((v) => v.syncState);
    const failedList = vendors.filter((v) => !v.syncState);
    return (
      <Modal
        wrapClassName="multiple-vendor-selector"
        className="multiple-vendor-content"
        visible={visible}
        closable
        title={messages("request-1.key882") /*请选择供应商*/}
        width={760}
        onCancel={this.onCancel}
        footer={<Button onClick={this.onCancel}>取消</Button>}
      >
        <Spin spinning={loading}>
          <div className="multiple-vendor-body">
            <Alert
              message={messages("request-1.key883") /*请避免重复预订，以免造成不必要的损失*/}
              type="warning"
              showIcon
            />
            <If value={succeedList.length > 0}>
              <div className="list content-success">
                <div className="sub-title">
                  {
                    messages(
                      "request-1.key884"
                    ) /*若您的公司要求要关联申请单，您可以选择以下审批单同步成功的服务商进行预订：*/
                  }
                </div>
                {this.renderVenderCards(succeedList)}
              </div>
            </If>
            <If value={failedList.length > 0}>
              <div className="list content-failed">
                <div className="sub-title">
                  {messages("request-1.key885") /*以下服务商审批单尚未同步，可能会影响您的预订：*/}
                  <div className="btn-refresh" onClick={this.fetchSyncResult}>
                    <Icon type="sync" style={{ color: "#2B78FF", marginRight: "5px" }} />
                    {messages("request-1.key823") /*刷新*/}
                  </div>
                </div>
                {this.renderVenderCards(failedList)}
              </div>
            </If>
          </div>
        </Spin>
      </Modal>
    );
  }
}
